﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ToolUtil
{
    public class WinMessageUtil
    {
        public const int WM_COPYDATA = 0x004A;
        //通过窗⼝的标题来查找窗⼝的句柄
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);
        //在DLL库中的发送消息函数
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage
        (
        int hWnd, // ⽬标窗⼝的句柄
        int Msg, // 在这⾥是WM_COPYDATA
        int wParam, // 第⼀个消息参数
        ref CopyDataStruct lParam // 第⼆个消息参数
        );


        /// <summary>
        /// 发送消息，只能传递⼀个⾃定义的消息ID和消息字符串，想传⼀个结构，但没成功
        /// </summary>
        /// <param name="destProcessName">⽬标进程名称，如果有多个，则给每个都发送</param>
        /// <param name="msgID">⾃定义数据，可以通过这个来决定如何解析下⾯的strMsg</param>
        /// <param name="strMsg">传递的消息，是⼀个字符串</param>
       
        public static void SendMessage(string lpClassName, string lpWindowName,int msgID, string strMsg)
        {
            if (strMsg == null) return;
            int hwnd = FindWindow("SerGdlisXP.Form1", lpWindowName);
            try{
                CopyDataStruct cds = new CopyDataStruct();
                cds.dwData = (IntPtr)msgID; //这⾥可以传⼊⼀些⾃定义的数据，但只能是4字节整数
                cds.lpData = strMsg; //消息字符串
                cds.cbData = System.Text.Encoding.Default.GetBytes(strMsg).Length + 1; //注意，这⾥的长度是按字节来算的
                                                                                       //发送⽅的窗⼝的句柄, 由于本系统中的接收⽅不关⼼是该消息是从哪个窗⼝发出的，所以就直接填0了
                int fromWindowHandler = 0;
                SendMessage(hwnd, WM_COPYDATA, fromWindowHandler, ref cds);
            }catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// 接收消息，得到消息字符串
        /// </summary>
        /// <param name="m">System.Windows.Forms.Message m</param>
        /// <returns>接收到的消息字符串</returns>
        public static string ReceiveMessage(ref System.Windows.Forms.Message m)
        {
            string lpData = "";
            switch (m.Msg)
            {
                case WM_COPYDATA:
                    CopyDataStruct cds = new CopyDataStruct();
                    Type myType = cds.GetType();
                    cds = (CopyDataStruct)m.GetLParam(myType);
                    lpData = cds.lpData;
                    break;
                default:
                    ReceiveMessage(ref m);
                    break;
            }
            return lpData;
        }
    }
}
